package com.zzq.my.jetpacks.jectpackapp.ui.act

import android.util.Log
import android.view.View
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import by.kirich1409.viewbindingdelegate.viewBinding
import com.aisier.architecture.base.BaseActivity
import com.blankj.utilcode.util.SPUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.zzq.my.jetpacks.jectpackapp.R
import com.zzq.my.jetpacks.jectpackapp.databinding.ActivityHttpBinding
import com.zzq.my.jetpacks.jectpackapp.net.findBanner.FindBannerViewModel
import com.zzq.my.jetpacks.jectpackapp.net.loadCaptcha.LoadCaptchaViewModel
import com.zzq.my.jetpacks.jectpackapp.net.loadindexdata.LoadIndexDataViewModel
import com.zzq.my.jetpacks.jectpackapp.net.login.LoginViewModel
import com.zzq.my.jetpacks.jectpackapp.net.submitfeedback.SubmitFeedbackViewModel
import com.zzq.my.jetpacks.net.base.RetrofitClient
import com.zzq.my.jetpacks.util.showMsg
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import me.jessyan.progressmanager.ProgressListener
import me.jessyan.progressmanager.ProgressManager
import me.jessyan.progressmanager.body.ProgressInfo
import okhttp3.Request
import okhttp3.Response
import java.io.BufferedInputStream
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream

/**
 * 描述：Retrofit2.0+协程的请求封装
 * 作者：zhuangzeqin
 * 时间: 2022/1/18-17:04
 * 邮箱：zzq@eeepay.cn
 * 备注:
 */
class HttpAct : BaseActivity(R.layout.activity_http), View.OnClickListener {
    private val binding by viewBinding(ActivityHttpBinding::bind)
    private val mLoginViewModel by viewModels<LoginViewModel>()
    private val mLoadIndexDataVM by viewModels<LoadIndexDataViewModel>()
    private val mFindBannerViewModel by viewModels<FindBannerViewModel>()
    private val mLoadCaptchaViewModel by viewModels<LoadCaptchaViewModel>()
    private val mSubmitFeedbackViewModel by viewModels<SubmitFeedbackViewModel>()
    private val mDownloadUrl = "https://pics5.baidu.com/feed/8435e5dde71190efb6d2c16a6d795c1ffcfa60c2.jpeg?token=e80f4ce45748f88a29fb783487ba016c"
    private var mLastDownloadingInfo: ProgressInfo? = null
    /**
     * 初始化数据
     */
    override fun initData() {
        /* ------注释说明---登录信息回调----- */
        mLoginViewModel.userLiveData.observeState(this) {
            onSuccess { code, message, dataBean, count ->
                // 登录成功过后 token 存放起来
                SPUtils.getInstance("SPUtils").put("token", dataBean?.loginToken)
                SPUtils.getInstance("SPUtils").put("agent_no", dataBean?.agentNo)
                binding.stvItemMsg.text = "msg:${dataBean.toString()}"
            }
            onFailed { code, message, dataBean, count ->
                binding.stvItemMsg.text = "msg:${message.toString()}"
            }
            onException {
                binding.stvItemMsg.text = it.message
            }
            onComplete {
                dismissLoading()
            }
        }
        /* ------注释说明--获取首页数据显示------ */
        mLoadIndexDataVM.LoadIndexDataLiveData.observeState(this)
        {
            onSuccess { code, message, loadIndexInfo, count ->
                binding.stvItemMsg.text = "msg:${loadIndexInfo.toString()}"
            }
            onFailed { code, message, dataBean, count ->
                binding.stvItemMsg.text = "msg:${message.toString()}"
            }
            onException {
                binding.stvItemMsg.text = it.message
            }
        }

        mFindBannerViewModel.bannerInfoLiveData.observeState(this)
        {
            onSuccess { code, message, listData, count ->
                binding.stvItemMsg.text = "msg:${listData?.size.toString()}-${listData.toString()}"
            }
            onFailed { code, message, listData, count ->
                binding.stvItemMsg.text = "msg:${message.toString()}"
            }
            onException {
                binding.stvItemMsg.text = it.message
            }
        }


//        mFindBannerViewModel.bannerInfoLiveData2.observerKt{
//            binding.stvItemMsg.text = "msg:${it?.size.toString()}-${it?.get(0).toString()}"
//        }
        //多数据源合并
        mFindBannerViewModel.mediatorLiveDataLiveData.observerKt {
            binding.stvItemMsg.text = "msg:${it?.size.toString()}-${it?.get(0).toString()}"
        }
        /* ------注释说明-图形验证码------- */
        mLoadCaptchaViewModel.loadCaptchaLiveData.observerKt{
            Glide.with(mContext).asGif().load(it).diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                .into(binding.ivCaptcha)
        }

        mSubmitFeedbackViewModel.submitFeedbackLiveData.observeState(this)
        {

            onSuccess { code, message, data, count ->
                showMsg(data)
                binding.stvItemMsg.text = "msg:${data}"
            }

            onFailed { code, message, data, count ->
                showMsg(message)
                binding.stvItemMsg.text = "msg:${message}"
            }

            onException {
                binding.stvItemMsg.text = it.message
            }

            onEmpty {
                binding.stvItemMsg.text = "msg:提交成功！"
            }


        }


    }

    /**
     * 初始化操作
     */
    override fun initView() {

        // Okhttp/Retofit 下载监听
//        ProgressManager.getInstance().addResponseListener(DOWNLOAD_URL, getDownloadListener());
        ProgressManager.getInstance().addResponseListener(mDownloadUrl,object : ProgressListener{
            /**
             * 进度监听
             *
             * @param progressInfo 关于进度的所有信息
             */
            override fun onProgress(progressInfo: ProgressInfo?) {
                // 如果你不屏蔽用户重复点击上传或下载按钮,就可能存在同一个 Url 地址,上一次的上传或下载操作都还没结束,
                // 又开始了新的上传或下载操作,那现在就需要用到 id(请求开始时的时间) 来区分正在执行的进度信息
                // 这里我就取最新的下载进度用来展示,顺便展示下 id 的用法
                if (mLastDownloadingInfo == null) {
                    mLastDownloadingInfo = progressInfo
                }

                //因为是以请求开始时的时间作为 Id ,所以值越大,说明该请求越新
                if (progressInfo!!.id < mLastDownloadingInfo!!.id) {
                    return
                } else if (progressInfo.id > mLastDownloadingInfo!!.id) {
                    mLastDownloadingInfo = progressInfo
                }

                val progress = mLastDownloadingInfo!!.percent
//                        mDownloadProgress.setProgress(progress)
                binding.stvItemMsg.text="$progress%"
                Log.d(
                    TAG,
                    "--Download-- " + progress + " %  " + mLastDownloadingInfo!!.speed + " byte/s  " + mLastDownloadingInfo.toString()
                )
                if (mLastDownloadingInfo!!.isFinish) {
                    //说明已经下载完成
                    Log.d(TAG, "--Download-- finish")
                    val file = File("/mnt/sdcard/eeepay_images/","123.jpeg")
                    Glide.with(mContext).load(file).into(binding.ivCaptcha)


                }
            }

            /**
             * 错误监听
             *
             * @param id 进度信息的 id
             * @param e 错误
             */
            override fun onError(id: Long, e: Exception?) {
                TODO("Not yet implemented")
            }
        })
    }

    /**
     * 初始化点击事件操作
     */
    override fun eventOnClick() {
        binding.stvItemLogin.setOnClickListener(this)
        binding.stvItemPost.setOnClickListener(this)
        binding.stvItemGet.setOnClickListener(this)
        binding.stvItemGetImageCode.setOnClickListener(this)
        binding.stvItemParameterImage.setOnClickListener(this)
        binding.stvItemDownload.setOnClickListener(this)


    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.stv_item_login -> {
                showLoading()
                mLoginViewModel.login("19000000021", "Ceshi@123")
            }
            R.id.stv_item_post -> {
//                mFindBannerViewModel.reqFindBanner()
//                SPUtils.getInstance("SPUtils").remove("token")
                mFindBannerViewModel.reqFindBanner2()
                mFindBannerViewModel.reqFindBanner3()
            }
            R.id.stv_item_get -> {
//                SPUtils.getInstance("SPUtils").remove("token")
                mLoadIndexDataVM.reqLoadIndexData()
            }
            R.id.stv_item_getImageCode -> {
                mLoadCaptchaViewModel.reqLoadCaptcha()
            }
            R.id.stv_item_ParameterImage -> {//todo  参数+图片上传给后台
                val file = File("/mnt/sdcard/eeepay_images/","123.jpeg")
                val imageListPath = listOf<String>("/sdcard/news_article/11.jpg",file.absolutePath)
                mSubmitFeedbackViewModel.submitFeedback("4","1","测试一下","15019437369",imageListPath)
            }
            R.id.stv_item_download->
            {
                downloadStart()//开启下载
            }
        }
    }

    /**
     * 点击开始下载资源,为了演示,就不做重复点击的处理,即允许用户在还有进度没完成的情况下,使用同一个 url 开始新的下载
     */
    private fun downloadStart() {
        lifecycleScope.launch {
            withContext(Dispatchers.IO)
            {
                kotlin.runCatching {
//                Thread(Runnable {
                    val request: Request = Request.Builder().url(mDownloadUrl).build()
                    // 构建 OkHttpClient 时,将 OkHttpClient.Builder() 传入 with() 方法,进行初始化配置
                    val OkHttpClientInfo = ProgressManager.getInstance().with(RetrofitClient.getInstance().getOkHttpClient().newBuilder()).build()
                    val response: Response = OkHttpClientInfo.newCall(request).execute()

                    val `is`: InputStream = response.body?.byteStream()!!
                    //为了方便就不动态申请权限了,直接将文件放到CacheDir()中
                    val file = File("/mnt/sdcard/eeepay_images/","123.jpeg")
                    val fos = FileOutputStream(file)
                    val bis = BufferedInputStream(`is`)
                    val buffer = ByteArray(1024)
                    var len: Int
                    while (bis.read(buffer).also { len = it } != -1) {
                        fos.write(buffer, 0, len)
                    }
                    fos.flush()
                    fos.close()
                    bis.close()
                    bis

                    `is`.close()
//                }).start()
                }.onFailure {
                    it.printStackTrace()
                    //当外部发生错误时,使用此方法可以通知所有监听器的 onError 方法
                    ProgressManager.getInstance().notifyOnErorr(mDownloadUrl,  Exception(it))
                    //Throwable是Error和Exception的父类，用来定义所有可以作为异常被抛出来的类。
                }
            }

        }
//        lifecycleScope.launch(Dispatchers.IO) {
//            kotlin.runCatching {
////                Thread(Runnable {
//                    val request: Request = Request.Builder().url(mDownloadUrl).build()
//                    // 构建 OkHttpClient 时,将 OkHttpClient.Builder() 传入 with() 方法,进行初始化配置
//                    val OkHttpClientInfo = ProgressManager.getInstance().with(RetrofitClient.getInstance().getOkHttpClient().newBuilder()).build()
//                    val response: Response = OkHttpClientInfo.newCall(request).execute()
//
//                    val `is`: InputStream = response.body?.byteStream()!!
//                    //为了方便就不动态申请权限了,直接将文件放到CacheDir()中
//                    val file = File("/mnt/sdcard/eeepay_images/","123.jpeg")
//                    val fos = FileOutputStream(file)
//                    val bis = BufferedInputStream(`is`)
//                    val buffer = ByteArray(1024)
//                    var len: Int
//                    while (bis.read(buffer).also { len = it } != -1) {
//                        fos.write(buffer, 0, len)
//                    }
//                    fos.flush()
//                    fos.close()
//                    bis.close()
//                    `is`.close()
////                }).start()
//            }.onFailure {
//                it.printStackTrace()
//                //当外部发生错误时,使用此方法可以通知所有监听器的 onError 方法
//                ProgressManager.getInstance().notifyOnErorr(mDownloadUrl,  Exception(it))
//                //Throwable是Error和Exception的父类，用来定义所有可以作为异常被抛出来的类。
//            }
//        }
    }

}